import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { StorageService } from '../../../../common/storage.service';
import { concat } from 'rxjs/operator/concat';
import { TemplateService } from '../template.service';
import { Check } from '../../../../common/check';
import { filter } from 'rxjs/operator/filter';
import { forEach } from '@angular/router/src/utils/collection';


@Component({
  selector: 'app-edit-formworker',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css'],
  providers: [Check, TemplateService]
})

export class TemplateEditComponent implements OnInit {
  loading; // 表格数据是否加载中
  templateId = 0; // 模板id
  pageSize; // 分页大小
  pageNo; // 当前页
  totalRecords; // 数据条数
  totalRecordsForNodes; // 节点数据条数
  editFlag: boolean = false; // 基本信息是否显示编辑页面
  editFlagBlocked: boolean = false; // 基本信息panel是否可用

  constructionStageData = []; // 施工阶段原数据
  constructionStageOperationData = []; // 施工阶段操作数据
  ConstructionStageCols = []; // 施工数据行头
  constructionEditFlag = false; // 施工阶段是否显示编辑页面
  deleteConstructionId = []; // 施工阶段要删出的施工阶段id
  constructionSortNum: number = 0; // 施工阶段排序的最大值
  constructionBlocked: boolean = false; // 阶段panel是否可用

  acceptanceItemData = []; // 验收项原数据
  acceptanceItemOperationData = []; // 验收项操作数据
  acceptanceItemStageCols = []; // 验收项数据行头
  acceptanceItemEditFlag = false; // 验收项是否显示编辑页面
  deleteAcceptanceItemId = []; // 验收项要删出的施工阶段id
  acceptanceItemSortNum: number = 0; // 验收项排序的最大值
  acceptanceItemBlocked: boolean = false; // 验收项panel是否可用
  checkSetData: any = {}; // 验收项去重
  nodeSetData: any = {}; // 节点去重

  checkChoiceData = []; // 选择验收弹框数据
  checkChoiceCols = []; // 选择验收项弹框列头
  nodesChoiceCols = []; // 节点弹框列头
  checkChoiceData1 = []; // 设置阶段验收项弹出层中的数据
  acceptanceItemSelectedData = []; // 弹出框中选中的数据
  checkChoiceFlag = false; // 选择验收项弹框打开状态
  baseId; // 模板id
  templateData: any = {}; // 模板详情
  templateDataBack: any = {}; // 模板详情返回数据
  tempData: any = []; // 交款模板
  orgData: any = []; // 组织信息
  selectedPayTemplateName; // 选中的交款模板
  payTemplateNameArr = []; // 所有交款模板数据
  payNameArr = []; // 所有交款模板数据

  stageSelectedCheck = []; // 阶段设置选中验收项弹框选中值

  currentEditStageId = 0; // 阶段设置 当前编辑的阶段id
  stagesSelectedCheckFlag = false; // 阶段设置 节点选择的弹出是否开启

  // 阶段设置临时假数据 使用接口后删除
  temStageData = [];

  stageData = []; // 所有阶段数据
  stageNodeListData = []; // 所有阶段数据对应的节点数据
  stageNodeListOperationtData = []; // 所有阶段数据对应的操作的节点数据
  stageNodeListHead = []; // 非编辑状态表格头
  stageNodeListEditHead = []; // 编辑状态表格头
  deletestageNodeListId = []; // 当前要删除的节点数据的id
  filesTree = []; // 报价模板
  targetCars: any = [];
  tavNextFlag = true; // tabview页是否可切换

  materialTree = []; // 物料tree原数据
  selectedMaterialTree = []; // 选中的物料数据
  // materialDatas = []; // 物料数据
  // 物料临时假数据 使用接口后删除
  temMaterialData = [];

  materialData = []; // 所有批次数据
  materialOperationtData = []; // 所有批次物料数据对应的操作的数据
  materialEditStageId = 0; // 物料设置 当前编辑的物料id
  MaterialDialog = false; // 选择物料的弹窗

  constructionSchedule = []; // 施工排期详情表头
  constructionScheduleEditHead = [];  // 施工排期编辑表头
  constructionScheduleFlag = false; // 施工排期是否显示编辑页面
  constructionScheduleData = []; // 施工排期原数据
  constructionScheduleOperationtData = []; // 施工排期操作数据
  nameError;
  selectNodesError; // 节点错误提示
  addConstructionStageError; // 施工阶段错误提示
  checkChoiceFlagsError; // 验收项错误提示
  constructionLimitDaysError; // 标准施工周期错误提示
  constructionLimitError; // 施工周期范围错误提示
  useAbleAreaError; // 适用面积错误提示
  priceTemplateError; // 报价模板错误提示
  payTemplateError; // 交款模板错误提示
  deliveryBatchNoError; // 送货批次错误提示

  daysOfArriveError; // 第几天到场错误提示
  earlyStartDaysError; // 提前启动天数错误提示
  materialListError; // 物料组错误提示
  autoReportDaysError; // 自动提报天数错误提示
  maxSupplyCycleError; // 最大供货周期错误提示

  constructDaysError; // 施工时长自动提示

  daysOfStartOptions = []; // 施工阶段设置-节点-施工时长/天
  sortNumOfBatchOptions = []; // 到必场批次下拉框数据
  paymentTemplateOptions = []; // 交款项下拉框数据
  isRequestPassItemOptions = []; // 必过下拉框数据
  isAutoReport = []; // 是否人工提报
  selectedIsAutoReport; // 选种后的是否人工提报
  isCustomConfirm = [{ name: '全部' }, { name: '是', code: true }, { name: '否', code: false }]; // 是否客户确认
  selectedIsCustomConfirm; // 选种后的是否客户确认
  isCustomDiscuss = [{ name: '全部' }, { name: '是', code: true }, { name: '否', code: false }]; // 是否客户评价
  selectedIsCustomDiscuss; // 选种后的是否客户评价
  searchObjCheck: any = {}; // 验收项查询条件
  isWarning = [{ name: '全部' }, { name: '是', code: true }, { name: '否', code: false }]; // 是否预警
  selectedIsWarning; // 选种后的是否预警
  isSupervisorConfirm = [{ name: '全部' }, { name: '是', code: true }, { name: '否', code: false }]; // 是否监理确认
  selectedIsSupervisorConfirm; // 选种后的是否监理确认
  searchObjNode: any = {}; // 节点查询条件
  keyWord = [];
  keyWordNode = []; // 节点弹框搜索
  W001 = false;
  editDayOfStart: any;


  organizationData = []; // 所有批次数据
  organizationOperationtData = []; // 所有组织数据对应的操作的数据
  organizationEditStageId = 0; // 组织设置 当前编辑的物料id
  organizationDialog = false; // 选择组织的弹窗
  organizationTree = []; // 组织tree原数据
  organizationListError;
  organizationError;

  selectedOrganizationTree = []; // 选中的组织数据
  // materialDatas = []; // 组织数据
  // 组  temMaterialData = [];织临时假数据 使用接口后删除


  // 操作列常量类
  columnoperation = { field: 'operation', header: '操作', width: '170px', tem: true };
  constructor(private router: Router, private storage: StorageService, private routeInfo: ActivatedRoute,
    private templateService: TemplateService, private check: Check, ) {
    // 施工阶段行头
    this.ConstructionStageCols = [
      { field: 'sort', header: '序号', width: '72px', tem: true },
      { field: 'name', header: '名称', width: '430px', editable: true, tem: true, required: true }
    ];

    // 验收项段行头
    this.acceptanceItemStageCols = [
      { field: 'sort', header: '序号', width: '72px', tem: true },
      { field: 'name', header: '名称', width: '430px', editable: true, tem: true, required: true }
    ];
    this.checkChoiceCols = [
      { field: 'code', header: '编号', width: '100px', frozen: false, sortable: true, tem: true },
      { field: 'name', header: '名称', frozen: false, sortable: true },
      { field: 'isWarning', header: '是否预警', width: '150px', sortable: true, tem: true },
      { field: 'isCustomDiscuss', header: '客户评价', sortable: true, tem: true },
      { field: 'isCustomBack', header: '客户回访', sortable: true, tem: true },
      { field: 'isCustomConfirm', header: '客户确认', sortable: true, tem: true },
    ];
    this.nodesChoiceCols = [
      { field: 'code', header: '编号', width: '100px', frozen: false, sortable: true, tem: true },
      { field: 'name', header: '名称', frozen: false, sortable: true },
      { field: 'referenceMoneyLimitCodes', header: '定额号', sortable: true, tem: true },
      { field: 'isWarning', header: '是否预警', width: '150px', sortable: true, tem: true },
      { field: 'isSupervisorConfirm', header: '是否监理确认', sortable: true, tem: true },
    ];
    // 非编辑状态表格头
    this.stageNodeListHead = [
      { field: 'sort', header: '序号', width: '72px', tem: true },
      { field: 'name', header: '名称', width: '430px', editable: true, tem: true },
      { field: 'daysOfStart', header: '第几天开始', width: '200px', editable: true, tem: true },
      { field: 'constructDays', header: '施工时长/天', width: '200px', editable: true, tem: true }
    ];
    // 编辑状态表格头
    this.stageNodeListEditHead = [
      { field: 'sort', header: '序号', width: '72px', tem: true },
      { field: 'name', header: '名称', width: '430px', tem: true },
      { field: 'daysOfStart', header: '第几天开始', width: '200px', editable: true, tem: true, required: true },
      { field: 'constructDays', header: '施工时长/天', width: '200px', editable: true, tem: true, required: true },
      { field: 'operation', header: '操作', width: '170px', tem: true }
    ];

    // 施工排期非编辑表格头
    this.constructionSchedule = [
      { field: 'sort', header: '序号', width: '92px', tem: true },
      { field: 'name', header: '施工进度', width: '412px', editable: false, tem: true },
      { field: 'constructDays', header: '施工时长/天', width: '160px', editable: true, tem: true },
      { field: 'isRequestPassItem', header: '是否必过', width: '150px', editable: true, tem: true },
      { field: 'sortNumOfBatch', header: '必到场批次', width: '140px', editable: true, tem: true },
      { field: 'needPayCode', header: '必交款项', width: '136px', editable: true, tem: true },
      { field: 'triggerPayCode', header: '触发交款', width: '130px', editable: true, tem: true },
    ];

    // 施工排期编辑表格头
    this.constructionScheduleEditHead = [
      { field: 'sort', header: '序号', width: '92px', tem: true },
      { field: 'name', header: '施工进度', width: '412px', editable: false, tem: true },
      { field: 'constructDays', header: '施工时长/天', width: '160px', editable: true, tem: true, required: true },
      { field: 'isRequestPassItem', header: '是否必过', width: '150px', editable: true, tem: true, required: true },
      { field: 'sortNumOfBatch', header: '必到场批次', width: '160px', editable: true, tem: true },
      { field: 'needPayCode', header: '必交款项', width: '160px', editable: true, tem: true },
      { field: 'triggerPayCode', header: '触发交款', width: '160px', editable: true, tem: true },
      { field: 'operation', header: '操作', width: '200px', tem: true },
    ];
    this.isAutoReport = [{ name: '是', code: true }, { name: '否', code: false }]; // 是否人工提报
  }

  ngOnInit() {
    this.storage.loading();
    // 获取路由id
    this.routeInfo.params.subscribe((params) => {
      this.baseId = params.id;
      // 获取模板信息
      this.templateService.templateConfigDetail(this.baseId).then(
        data => {
          if (data.result) {
            this.storage.loadout();
            this.targetCars = JSON.parse(JSON.stringify(data.data.templateData.retPriceData));
            this.tempData = JSON.parse(JSON.stringify(data.data.templateData.retPriceData));
            this.orgData = this.organizationOperationtData = data.data.templateData.retOrganizationData;
            this.templateData = data.data.templateData;
            this.templateDataBack = JSON.parse(JSON.stringify(this.templateData));
            this.selectedPayTemplateName = { code: data.data.templateData.payTemplateCode, id: data.data.templateData.payTemplateId };
          } else {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );
      // 获取施工阶段信息
      this.templateService.stageList(this.baseId).then(
        data => {
          if (data.result) {
            this.storage.loadout();
            this.constructionStageData = data.data;
            if (this.constructionStageData.length > 0) {
              this.constructionSortNum = this.constructionStageData[this.constructionStageData.length - 1].sortNum;
            } else {
              this.constructionSortNum = 0;
            }
            this.constructionStageOperationData = JSON.parse(JSON.stringify(this.constructionStageData));
          } else {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败' });
          }
        }
      );
      // 获取验收项信息
      this.templateService.findTempChechList(this.baseId).then(
        data => {
          if (data.result) {
            this.storage.loadout();
            this.acceptanceItemData = data.data;
            if (this.acceptanceItemData.length > 0) {
              this.acceptanceItemSortNum = this.acceptanceItemData[this.acceptanceItemData.length - 1].sortNum;
            } else {
              this.acceptanceItemSortNum = 0;
            }
            this.acceptanceItemOperationData = JSON.parse(JSON.stringify(this.acceptanceItemData));
          } else {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );
      // 初始化报价模板
      this.templateService.findPriceTemplate().then(
        data => {
          if (data.result) {
            this.storage.loadout();
            this.filesTree = data.data;
            this.filesTree = this.filesTree.filter((item) => {
              return this.targetCars.includes(item);
            });
          } else {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );
      // 初始化交款模板
      this.templateService.findTemplateList().then(
        data => {
          if (data.result) {
            this.storage.loadout();
            this.payTemplateNameArr = JSON.parse(JSON.stringify(data.data));
          } else {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );

      // 初始化必交款
      this.templateService.findPayList().then(
        data => {
          if (data.result) {
            this.storage.loadout();
            this.payNameArr = JSON.parse(JSON.stringify(data.data));
          } else {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );

    });
  }

  handleChange(event) {
  }
  onPage(event) {


  }
  // 初始化报价模板数据
  onClickPrice() {
    this.storage.loading();
    // 初始化报价模板
    this.templateService.findPriceTemplate().then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.filesTree = data.data;
          this.filesTree = this.filesTree.filter((item) => {
            return !this.targetCars.some((tem) => {
              return tem.code === item.code;
            });
          });
          this.W001 = true;
        } else {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }
  initTemplateData() {
    // 获取模板信息
    this.templateService.templateConfigDetail(this.baseId).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.targetCars = JSON.parse(JSON.stringify(data.data.templateData.retPriceData));
          this.tempData = JSON.parse(JSON.stringify(data.data.templateData.retPriceData));
          this.templateData = data.data.templateData;
          this.templateDataBack = JSON.parse(JSON.stringify(this.templateData));
          this.selectedPayTemplateName = { code: data.data.templateData.payTemplateCode, id: data.data.templateData.payTemplateId };
        } else {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }

  // 保存模板
  saveTement() {
    this.tempData = JSON.parse(JSON.stringify(this.targetCars));
    if (this.tempData.length > 0) {
      this.priceTemplateError = '';
    }
    this['W001'] = false;
  }

  onRemove(data) {
    this.tempData = this.tempData.filter((item) => {
      if (item.id === data.id) {
        this.filesTree = [...this.filesTree, item];
        return false;
      } else { return true; }
    });
    this.targetCars = this.tempData.concat([]);
  }
  // 验收项搜索
  searchCheck() {
    if (this.selectedIsCustomConfirm) {
      this.searchObjCheck['isCustomConfirm'] = this.selectedIsCustomConfirm.code;
    } else {
      delete this.searchObjCheck['isCustomConfirm'];
    }
    if (this.selectedIsCustomDiscuss) {
      this.searchObjCheck['isCustomDiscuss'] = this.selectedIsCustomDiscuss.code;
    } else {
      delete this.searchObjCheck['isCustomDiscuss'];
    }
    if (this.keyWord) {
      this.searchObjCheck['searchValue'] = this.keyWord;
    } else {
      delete this.searchObjCheck['searchValue'];
    }
    this.searchObjCheck['checkSetData'] = this.acceptanceItemOperationData;
    this.templateService.findCheckList(this.searchObjCheck, this.pageSize, this.pageNo).then(
      data => {
        if (data.result) {
          this.checkChoiceData = data.data.list;
          this.totalRecords = data.data.totalCount;
        } else {
          this.checkChoiceData = [];
          this.totalRecords = 0;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }
  // 验收项list
  checkChoiceFlags() {
    this.checkSetData['checkSetData'] = this.acceptanceItemOperationData;
    this.storage.loading();
    this.templateService.findCheckList(this.checkSetData, this.pageSize, this.pageNo).then(
      data => {
        if (data.result) {
          this.checkChoiceFlag = true;
          this.checkChoiceData = data.data.list;
          this.totalRecords = data.data.totalCount;
        } else {
          this.checkChoiceData = [];
          this.totalRecords = 0;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
        this.storage.loadout();
      }
    );
  }
  // 节点搜索
  searchNode() {
    if (this.selectedIsWarning) {
      this.searchObjNode['isWarning'] = this.selectedIsWarning.code;
    } else {
      delete this.searchObjNode['isWarning'];
    }
    if (this.selectedIsSupervisorConfirm) {
      this.searchObjNode['isSupervisorConfirm'] = this.selectedIsSupervisorConfirm.code;
    } else {
      delete this.searchObjNode['isCustomDiscuss'];
    }
    if (this.keyWordNode) {
      this.searchObjNode['searchValue'] = this.keyWordNode;
    } else {
      delete this.searchObjNode['searchValue'];
    }
    let tem = [];
    for (let item of this.stageNodeListOperationtData) {
      tem = [...tem, ...item.data];
    }
    this.searchObjNode['nodeSetData'] = tem;
    this.templateService.findNodeList(this.searchObjNode, this.pageSize, this.pageNo).then(
      data => {
        if (data.result) {
          this.checkChoiceData1 = data.data.list;
          this.totalRecordsForNodes = data.data.totalCount;
        } else {
          this.checkChoiceData1 = [];
          this.totalRecordsForNodes = 0;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }
  // 施工阶段设置节点弹框
  selectNodes() {
    let tem = [];
    for (let item of this.stageNodeListOperationtData) {
      tem = [...tem, ...item.data];
    }
    this.storage.loading();
    this.nodeSetData['nodeSetData'] = tem;
    this.templateService.findNodeList(this.nodeSetData, this.pageSize, this.pageNo).then(
      data => {
        if (data.result) {
          this.totalRecordsForNodes = data.data.totalCount;
          this.checkChoiceData1 = JSON.parse(JSON.stringify(data.data.list));
          this.stagesSelectedCheckFlag = true;
        } else {
          this.checkChoiceData1 = [];
          this.totalRecordsForNodes = 0;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
        this.storage.loadout();
      }
    );

  }

  /**
   * 添加施工阶段
   */
  addConstructionStage() {
    this.addConstructionStageError = '';
    // 计算最大排序值
    this.constructionSortNum = this.constructionSortNum + 1;
    const stage = {
      content: '', sortNum: this.constructionSortNum
    };
    this.constructionStageOperationData = [...this.constructionStageOperationData, stage];
  }


  /**
   * 编辑页面显示
   * @param event
   */
  update(event, id?) {
    // const table = event.target.dataset.table || event.target.parentNode.dataset.table;

    switch (event) {
      // 基础设置-施工阶段
      case 'stage':
        this.addConstructionStageError = '';
        // 页面进入编辑状态
        this.constructionEditFlag = !this.constructionEditFlag;
        // 添加操作列
        this.ConstructionStageCols = [...this.ConstructionStageCols, this.columnoperation];
        // 还原排序的最大值
        this.constructionSortNum = this.constructionStageData.length > 0 ?
          this.constructionStageData[this.constructionStageData.length - 1].sortNum : 0;
        // 删除数据id清空
        this.deleteConstructionId = [];
        this.setBlockedTrueByPars('stage');
        break;
      // 基础设置-验收项
      case 'check':
        this.checkChoiceFlagsError = '';
        // 页面进入编辑状态
        this.acceptanceItemEditFlag = !this.acceptanceItemEditFlag;
        // 添加操作列
        this.acceptanceItemStageCols = [...this.acceptanceItemStageCols, this.columnoperation];
        // 还原排序的最大值
        this.acceptanceItemSortNum = this.acceptanceItemData.length > 0 ?
          this.acceptanceItemData[this.acceptanceItemData.length - 1].sortNum : 0;
        // 删除数据id清空
        this.deleteAcceptanceItemId = [];
        this.setBlockedTrueByPars('check');
        break;
      case 'info':
        this.setErrorNull();
        this.setBlockedTrueByPars('info');
        this.tempData = JSON.parse(JSON.stringify(this.templateData.retPriceData));
        this.targetCars = JSON.parse(JSON.stringify(this.templateData.retPriceData));
        this.organizationOperationtData = JSON.parse(JSON.stringify(this.templateData.retOrganizationData));
        this.selectedPayTemplateName = JSON.parse(JSON.stringify(this.templateData.payTemplateData));
        // 添加操作列
        // this.acceptanceItemStageCols = [...this.acceptanceItemStageCols, this.columnoperation];
        this.editFlag = !this.editFlag;
        break;
      case 'stageList':
        this.selectNodesError = '';
        if (id.constructDays || id.constructDays === 0) {
          this.currentEditStageId = id.id;
          this.setBlockedTrueByPars('stageList', id.id);
          this.stageListFlagById(id.id);
        } else {
          this.storage.makesureService.emit({
            message: '请先进行工程排期，再进行施工节点设置！',
            header: '提示',
            rejectVisible: false,
            acceptVisible: false,
            accept: () => {
            }
          });
        }
        break;
      case 'materialList':
        this.setErrorNull();
        this.materialEditStageId = id;
        this.setBlockedTrueByPars('materialList', id);
        this.materialListFlagById(id);
        break;
      case 'construction':
        this.constructionScheduleFlag = !this.constructionScheduleFlag;
        this.tavNextFlag = false;
        break;
    }
  }



  /**
   *  所有状态改变为可用状态
   */
  setBlockedFalse(info) {
    switch (info) {
      // 阶段设置
      case 'stage':
        for (const item of this.stageData) {
          item['stageBlocked' + item.id] = false;
        }
        break;
      // 阶段设置
      case 'material':
        for (const item of this.materialData) {
          item['materialBlocked' + item.id] = false;
        }
        break;
      case 'base':
        // 阶段可操作
        this.constructionBlocked = false;
        // 验收信息可操作
        this.acceptanceItemBlocked = false;
        // 基本信息可操作
        this.editFlagBlocked = false;
        break;
    }
    this.tavNextFlag = true;
  }

  /**
   * 根据传入参数确定，那个模块进入不可操作状态
   * @param info
   */
  setBlockedTrueByPars(info, id?) {
    this.tavNextFlag = false;
    switch (info) {
      // 施工阶段
      case 'stage':
        // 基本信息不可操作
        this.editFlagBlocked = true;
        // 验收信息不可操作
        this.acceptanceItemBlocked = true;
        break;
      // 基础
      case 'info':
        // 阶段不可操作
        this.constructionBlocked = true;
        // 验收信息不可操作
        this.acceptanceItemBlocked = true;
        break;
      // 验收
      case 'check':
        // 基本信息不可操作
        this.editFlagBlocked = true;
        // 阶段不可操作
        this.constructionBlocked = true;
        break;
      case 'stageList':
        // 循环处理处选中节点可操作。其他节点不可操作
        for (const item of this.stageData) {
          if (item.id === id) {
            item['stageBlocked' + item.id] = false;
          } else {
            item['stageBlocked' + item.id] = true;
          }
        }
        break;
      case 'materialList':
        // 循环处理处选中节点可操作。其他节点不可操作
        for (const item of this.materialData) {
          if (item.id === id) {
            item['materialBlocked' + item.id] = false;
            this.selectedIsAutoReport = { code: item.isAutoReport };
          } else {
            item['materialBlocked' + item.id] = true;
          }
        }
        break;
    }
  }
  /**
   * 展示页面显示
   * @param event
   */
  back(event, id?) {
    switch (event) {
      // 基础设置-施工阶段
      case 'stage':
        this.constructionEditFlag = !this.constructionEditFlag;
        // 操作按钮列移除
        this.ConstructionStageCols.pop();
        // 操作数据还原成原数据
        this.constructionStageOperationData = JSON.parse(JSON.stringify(this.constructionStageData));
        // 还原排序的最大值
        this.constructionSortNum = this.constructionStageData.length > 0 ?
          this.constructionStageData[this.constructionStageData.length - 1].sortNum : 0;
        // 删除数据id清空
        this.deleteConstructionId = [];
        this.setBlockedFalse('base');
        break;
      // 基础设置-验收项
      case 'check':
        this.acceptanceItemEditFlag = !this.acceptanceItemEditFlag;
        // 操作按钮列移除
        this.acceptanceItemStageCols.pop();
        // 操作数据还原成原数据
        this.acceptanceItemOperationData = JSON.parse(JSON.stringify(this.acceptanceItemData));
        // 还原排序的最大值
        this.acceptanceItemSortNum = this.acceptanceItemData.length > 0 ?
          this.acceptanceItemData[this.acceptanceItemData.length - 1].sortNum : 0;
        // 删除数据id清空
        this.deleteAcceptanceItemId = [];
        this.setBlockedFalse('base');
        break;
      case 'info':
        this.templateDataBack = JSON.parse(JSON.stringify(this.templateData));
        this.editFlag = !this.editFlag;
        this.setBlockedFalse('base');
        break;
      case 'stageList':
        this.stageListFlagById(id);
        this.setBlockedFalse('stage');
        this.stageNodeListOperationtData = JSON.parse(JSON.stringify(this.stageNodeListData));
        this.currentEditStageId = 0;
        break;
      case 'materialList':
        this.materialListFlagById(id);
        this.setBlockedFalse('material');
        this.materialOperationtData = JSON.parse(JSON.stringify(this.materialData));
        this.currentEditStageId = 0;
        break;
      case 'construction':
        // 施工排期原数据
        this.constructionScheduleOperationtData = JSON.parse(JSON.stringify(this.constructionScheduleData));
        this.constructionScheduleFlag = !this.constructionScheduleFlag;
        this.tavNextFlag = true;
        break;
    }
  }

  /**
   * 阶段设置 节点删除
   * @param data 单行数据
   * @param id 阶段id
   */
  removeStageItem(data, id) {
    if (data.nodeId) {
      this.storage.makesureService.emit({
        message: '保存时关联的内容也将同步删除',
        header: '提示',
        acceptLabel: '确认',
        rejectLabel: '取消',
        rejectVisible: true,
        accept: () => {
          this.reomveStafeData(data, id);
        }
      });
    } else {
      this.reomveStafeData(data, id);
    }
  }
  reomveStafeData(data, id) {
    // 如果有id 将id保存在删除数组中，用于后台删除。
    if (data.id) {
      this.deletestageNodeListId = [...this.deletestageNodeListId, data.id];
    }
    for (let item of this.stageNodeListOperationtData) {
      if (item.id === id) {
        item.data = item.data.filter((i) => {
          if (i.nodeId) {
            if (i.nodeId === data.nodeId) {
              return false;
            } else {
              return true;
            }
          } else {
            if (i.id === data.id) {
              return false;
            } else {
              return true;
            }
          }

        });
        break;
      }
    }
  }

  /**
   * 计算施工时长下拉框中的数据
   * @param data
   */
  calculate(data, constructDays) {
    if (data.daysOfStart == this.editDayOfStart) {
      return;
    }
    if (data.daysOfStart !== null && data.daysOfStart !== undefined && constructDays !== null && constructDays !== undefined) {
      if (data.constructDays && data.constructDays >= 0) {
        data['selectedConstructDays'] = { code: 1, value: data.constructDays };
      } else {
        data['selectedConstructDays'] = {};
      }
      let constructDaysOptions = [];
      if (data.daysOfStart && data.daysOfStart >= 0) {
        for (let i = 0; i <= constructDays - data.daysOfStart; i++) {
          constructDaysOptions = [...constructDaysOptions, { code: i + 1, value: i + 1 }];
        }
      }
      data['constructDaysOptions'] = JSON.parse(JSON.stringify(constructDaysOptions));
      data['selectedConstructDays'] = {};
    }
  }

  validateDayOfStart(data) {
    data.daysOfStart = data.daysOfStart + '';
    data.daysOfStart = data.daysOfStart.replace(/[^0-9-]+/, '');
    if (!parseInt(data.daysOfStart, 0)) {
      data.daysOfStart = '';
    }
  }
  /**
   *  阶段设置 节点下移
   * @param data 单行数据
   * @param index 要做操作数据的位置
   * @param id 阶段id
   */
  downStageItem(data, index, id) {
    for (let item of this.stageNodeListOperationtData) {
      if (item.id === id) {
        if (index === item.data.length - 1) {
          // this.error('已经是最后一行了！');
          break;
        }
        let currentNodeList = JSON.parse(JSON.stringify(item.data));
        // sortNum顺序调换
        const temSortNum = currentNodeList[index]['sortNum'];
        currentNodeList[index]['sortNum'] = currentNodeList[index + 1]['sortNum'];
        currentNodeList[index + 1]['sortNum'] = temSortNum;
        // 数据位置顺序调换
        const doc = currentNodeList.splice(index, 1);
        currentNodeList.splice(index + 1, 0, doc[0]);
        currentNodeList = [...currentNodeList];
        item.data = currentNodeList;
        break;
      }
    }
  }
  /**
   *  阶段设置 节点上移
   * @param data 单行数据
   * @param index 要做操作数据的位置
   * @param id 阶段id
   */
  upStageItem(data, index, id) {
    if (index === 0) {
      // this.error('已经是第一行了！');
      return;
    }
    for (let item of this.stageNodeListOperationtData) {
      if (item.id === id) {
        let currentNodeList = JSON.parse(JSON.stringify(item.data));
        // sortNum顺序调换
        const temSortNum = currentNodeList[index]['sortNum'];
        currentNodeList[index]['sortNum'] = currentNodeList[index - 1]['sortNum'];
        currentNodeList[index - 1]['sortNum'] = temSortNum;
        // 数据位置顺序调换
        const doc = currentNodeList.splice(index, 1);
        currentNodeList.splice(index - 1, 0, doc[0]);
        currentNodeList = [...currentNodeList];
        item.data = currentNodeList;
        break;
      }
    }
  }


  /**
   * 基本信息保存
   */
  infoSave() {
    // 保存施工阶段
    if (this.templateData.deliveryBatchNo === this.templateDataBack.deliveryBatchNo &&
      this.templateData.payTemplateId === this.selectedPayTemplateName['id']) {
      this.saveInfo();
    } else {
      this.retdata();
    }

  }
  // 校验交款模板
  payTemplateNameCk() {
    if (!(this.selectedPayTemplateName && this.selectedPayTemplateName['code'])) {
      this.payTemplateError = '交款模板不能为空！';
    } else {
      this.payTemplateError = '';
    }
  }
  saveInfo() {
    this.storage.loading();
    let ids = new Array();
    let priceCode = new Array();
    let organizationCode = new Array();
    for (let index of this.tempData) {
      ids.push(index.id);
      priceCode.push(index.code);
    }
    for (let index of this.organizationOperationtData) {
      organizationCode.push(index.code);
    }
    this.templateDataBack['priceTemplateId'] = ids.join(',');
    this.templateDataBack['priceTemplateCode'] = priceCode.join(',');
    this.templateDataBack['organizationCode'] = organizationCode.join(',');
    if (!this.checkSaveData()) {
      this.storage.loadout();
      return;
    }
    if (this.selectedPayTemplateName) {
      this.templateDataBack['payTemplateCode'] = this.selectedPayTemplateName.code;
      this.templateDataBack['payTemplateId'] = this.selectedPayTemplateName.id;
    } else {
      delete this.templateDataBack['payTemplateCode'];
      delete this.templateDataBack['payTemplateId'];
    }
    this.templateDataBack['id'] = this.baseId;
    this.templateService.updateTemplate({
      template: this.templateDataBack
    }).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
          // 清空文本框里所有的值
          this.back('info'); // 数据保存成功后调用这个方法
          this.initTemplateData();
          // this.templateData = data.data.templateData;
          // console.log('this.templateData', this.templateData);
          // this.templateDataBack = JSON.parse(JSON.stringify(this.templateData));
        } else {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: data.msg });
          this.nameError = data.msg;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }
  // 修改提示
  retdata() {
    this.storage.makesureService.emit({
      message: '修改交款模板或送货批次，保存后该模板的物料配送与工程排期需要重新设置，模板禁用',
      header: '提示',
      acceptLabel: '确认',
      rejectLabel: '取消',
      rejectVisible: true,
      accept: () => {
        this.saveInfo();
      }
    });
  }
  /**
  * 阶段保存方法
  */
  stageSave() {
    if (!this.checkStageData()) {
      return;
    }
    this.storage.loading();
    if (this.constructionStageOperationData.length === 0) {
      this.storage.loadout();
      this.addConstructionStageError = '请添加施工阶段';
      return;
    }
    // 保存施工阶段
    this.templateService.saveStage({
      delData: this.deleteConstructionId, list: this.constructionStageOperationData
      , baseId: this.baseId
    }).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.back('stage');
          this.constructionStageData = data.data;
          if (this.constructionStageData.length > 0) {
            this.constructionSortNum = this.constructionStageData[this.constructionStageData.length - 1].sortNum;
          } else {
            this.constructionSortNum = 0;
          }
          this.constructionStageOperationData = JSON.parse(JSON.stringify(this.constructionStageData));
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
          this.initTemplateData();
        } else {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: data.msg });
        }
      }
    );
    // 提交数据
    // console.log(this.constructionStageOperationData);
    // 删除的id集合
    // console.log(this.deleteConstructionId);
    // 保存成功后返回最新的数据必须保存到 原数据中 this.constructionStageData= 最新数据
    // this.back('stage'); // 数据保存成功后调用这个方法

  }
  // 校验施工阶段数据
  checkStageData(): boolean {
    let list = this.constructionStageOperationData;
    let flag = true;
    for (let index of list) {
      if (!index.name || index.name.length > 4) {
        flag = false;
      }
    }
    return flag;

  }

  /**
  * 验收保存方法
  */
  checkSave() {
    // if (this.acceptanceItemOperationData.length === 0) {
    //   return;
    // }
    this.storage.loading();
    if (this.acceptanceItemOperationData.length === 0) {
      this.storage.loadout();
      this.checkChoiceFlagsError = '请选择验收项';
      return;
    }
    // 保存施工阶段
    this.templateService.saveCheck({
      delData: this.deleteAcceptanceItemId, list: this.acceptanceItemOperationData
      , baseId: this.baseId
    }).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.back('check');
          this.acceptanceItemData = data.data;
          if (this.acceptanceItemData.length > 0) {
            this.acceptanceItemSortNum = this.acceptanceItemData[this.acceptanceItemData.length - 1].sortNum;
          } else {
            this.acceptanceItemSortNum = 0;
          }
          this.acceptanceItemOperationData = JSON.parse(JSON.stringify(this.acceptanceItemData));
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
          this.initTemplateData();
        } else {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: data.msg });
        }
      }
    );
    // 提交数据
    // console.log(this.acceptanceItemOperationData);
    // 删除的id集合
    // console.log(this.deleteAcceptanceItemId);
    // 保存成功后返回最新的数据必须保存到 原数据中  this.acceptanceItemData = 最新数据
    // this.back('check'); // 数据保存成功后调用这个方法

  }


  /**
  * 删除施工阶段
  * @param data 当前行数据
  */
  removeConstruction(data) {
    if (data.id) {
      this.storage.makesureService.emit({
        message: '保存时关联的内容也将同步删除',
        header: '提示',
        acceptLabel: '确认',
        rejectLabel: '取消',
        rejectVisible: true,
        acceptVisible: true,
        accept: () => {
          // 如果有id 将id保存在删除数组中，用于后台删除。
          if (data.id) {
            this.deleteConstructionId = [...this.deleteConstructionId, data.id];
          }
          // 将删除的数据保存在
          this.constructionStageOperationData = this.constructionStageOperationData.filter((item, index) => {
            if (item === data) {
              return false;
            } else {
              return true;
            }
          });
        }
      });
    } else {
      // 如果有id 将id保存在删除数组中，用于后台删除。
      if (data.id) {
        this.deleteConstructionId = [...this.deleteConstructionId, data.id];
      }
      // 将删除的数据保存在
      this.constructionStageOperationData = this.constructionStageOperationData.filter((item, index) => {
        if (item === data) {
          return false;
        } else {
          return true;
        }
      });
    }
  }


  /**
   * 下移施工阶段
   * @param data 当前行数据
   */
  moveDownConstruction(data, index) {
    if (index === this.constructionStageOperationData.length - 1) {
      // this.error('已经是最后一行了！');
      return;
    }
    // sortNum顺序调换
    const temSortNum = this.constructionStageOperationData[index]['sortNum'];
    this.constructionStageOperationData[index]['sortNum'] = this.constructionStageOperationData[index + 1]['sortNum'];
    this.constructionStageOperationData[index + 1]['sortNum'] = temSortNum;
    // 数据位置顺序调换
    const doc = this.constructionStageOperationData.splice(index, 1);
    this.constructionStageOperationData.splice(index + 1, 0, doc[0]);
    this.constructionStageOperationData = [...this.constructionStageOperationData];
  }

  /**
   * 上移施工阶段
   * @param data 当前行数据
   */
  moveUpConstruction(data, index) {
    if (index === 0) {
      // this.error('已经是第一行了！');
      return;
    }
    // sortNum顺序调换
    const temSortNum = this.constructionStageOperationData[index]['sortNum'];
    this.constructionStageOperationData[index]['sortNum'] = this.constructionStageOperationData[index - 1]['sortNum'];
    this.constructionStageOperationData[index - 1]['sortNum'] = temSortNum;
    // 数据位置顺序调换
    const doc = this.constructionStageOperationData.splice(index, 1);
    this.constructionStageOperationData.splice(index - 1, 0, doc[0]);
    this.constructionStageOperationData = this.constructionStageOperationData.concat([]);
  }


  /**
  * 删除验收项
  * @param data 当前行数据
  */
  removeAcceptanceItem(data) {
    if (data.checkId) {
      this.storage.makesureService.emit({
        message: '保存时关联的内容也将同步删除',
        header: '提示',
        acceptLabel: '确认',
        rejectLabel: '取消',
        rejectVisible: true,
        acceptVisible: true,
        accept: () => {
          // 如果有id 将id保存在删除数组中，用于后台删除。
          if (data.id) {
            this.deleteAcceptanceItemId = [...this.deleteAcceptanceItemId, data.id];
          }
          // 将删除的数据保存在
          this.acceptanceItemOperationData = this.acceptanceItemOperationData.filter((item, index) => {
            if (item === data) {
              return false;
            } else {
              return true;
            }
          });
        }
      });
    } else {
      // 如果有id 将id保存在删除数组中，用于后台删除。
      if (data.id) {
        this.deleteAcceptanceItemId = [...this.deleteAcceptanceItemId, data.id];
      }
      // 将删除的数据保存在
      this.acceptanceItemOperationData = this.acceptanceItemOperationData.filter((item, index) => {
        if (item === data) {
          return false;
        } else {
          return true;
        }
      });
    }
  }


  /**
   * 下移验收项
   * @param data 当前行数据
   */
  moveDownAcceptanceItem(data, index) {
    if (index === this.acceptanceItemOperationData.length - 1) {
      // this.error('已经是最后一行了！');
      return;
    }
    // sortNum顺序调换
    const temSortNum = this.acceptanceItemOperationData[index]['sortNum'];
    this.acceptanceItemOperationData[index]['sortNum'] = this.acceptanceItemOperationData[index + 1]['sortNum'];
    this.acceptanceItemOperationData[index + 1]['sortNum'] = temSortNum;
    // 数据位置顺序调换
    const doc = this.acceptanceItemOperationData.splice(index, 1);
    this.acceptanceItemOperationData.splice(index + 1, 0, doc[0]);
    this.acceptanceItemOperationData = [...this.acceptanceItemOperationData];
  }

  /**
   * 上移验收项
   * @param data 当前行数据
   */
  moveUpAcceptanceItem(data, index) {
    if (index === 0) {
      // this.error('已经是第一行了！');
      return;
    }
    // sortNum顺序调换
    const temSortNum = this.acceptanceItemOperationData[index]['sortNum'];
    this.acceptanceItemOperationData[index]['sortNum'] = this.acceptanceItemOperationData[index - 1]['sortNum'];
    this.acceptanceItemOperationData[index - 1]['sortNum'] = temSortNum;
    // 数据位置顺序调换
    const doc = this.acceptanceItemOperationData.splice(index, 1);
    this.acceptanceItemOperationData.splice(index - 1, 0, doc[0]);
    this.acceptanceItemOperationData = this.acceptanceItemOperationData.concat([]);
  }

  /**
   * 上移施工排期
   * @param data
   * @param index
   */
  moveUpSchedule(data, index) {
    if (index === 0) {
      // this.error('已经是第一行了！');
      return;
    }
    // sortNum顺序调换
    const temSortNum = this.constructionScheduleOperationtData[index]['sortNum'];
    this.constructionScheduleOperationtData[index]['sortNum'] = this.constructionScheduleOperationtData[index - 1]['sortNum'];
    this.constructionScheduleOperationtData[index - 1]['sortNum'] = temSortNum;
    // 数据位置顺序调换
    const doc = this.constructionScheduleOperationtData.splice(index, 1);
    this.constructionScheduleOperationtData.splice(index - 1, 0, doc[0]);
    this.constructionScheduleOperationtData = this.constructionScheduleOperationtData.concat([]);

  }

  /**
   * 下移施工排期
   * @param data
   * @param index
   */
  moveDownSchedule(data, index) {
    if (index === this.constructionScheduleOperationtData.length - 1) {
      // this.error('已经是最后一行了！');
      return;
    }
    // sortNum顺序调换
    const temSortNum = this.constructionScheduleOperationtData[index]['sortNum'];
    this.constructionScheduleOperationtData[index]['sortNum'] = this.constructionScheduleOperationtData[index + 1]['sortNum'];
    this.constructionScheduleOperationtData[index + 1]['sortNum'] = temSortNum;
    // 数据位置顺序调换
    const doc = this.constructionScheduleOperationtData.splice(index, 1);
    this.constructionScheduleOperationtData.splice(index + 1, 0, doc[0]);
    this.constructionScheduleOperationtData = [...this.constructionScheduleOperationtData];
  }



  /**
   * 选择验收项数据添加
   */
  addAcceptanceItem() {
    this.checkChoiceFlagsError = '';
    this.acceptanceItemSelectedData.filter((item) => {
      this.acceptanceItemSortNum = this.acceptanceItemSortNum + 1;
      item['sortNum'] = this.acceptanceItemSortNum;
    });
    this.acceptanceItemOperationData = JSON.parse(JSON.stringify([...this.acceptanceItemOperationData,
    ...this.acceptanceItemSelectedData]));
    this.checkChoiceFlag = false;
    this.acceptanceItemSelectedData = [];
    this.isCustomConfirm = [];
    this.isCustomDiscuss = [];
  }

  /**
   * 阶段设置 选择节点项数据添加
   */
  addCheckToStage() {
    this.selectNodesError = '';
    let stageTem;
    for (let item of this.stageData) {
      if (item.id === this.currentEditStageId) {
        stageTem = item;
        break;
      }
    }
    if (!stageTem) {
      return;
    }
    // 新加入的数据添加sortNum排序字段
    for (let item of this.stageNodeListOperationtData) {
      if (item.id === this.currentEditStageId) {
        let currentNodeList = JSON.parse(JSON.stringify(item.data));
        this.stageSelectedCheck.filter((current) => {
          stageTem['stageSortNum' + this.currentEditStageId] = stageTem['stageSortNum' + this.currentEditStageId] + 1;
          current['sortNum'] = stageTem['stageSortNum' + this.currentEditStageId];
        });
        item.data = [...item.data, ...this.stageSelectedCheck];
        break;
      }
    }
    this.stageSelectedCheck = [];
    this.stagesSelectedCheckFlag = false;
    this.selectedIsWarning = [];
    this.selectedIsSupervisorConfirm = [];
  }

  /**
   * 阶段设置  每个阶段数据的保存
   */
  saveStageNodes(id, constructDays) {
    let stageId = id; // 阶段id
    let nodeList = []; // 阶段下最新的节点数据
    for (const item of this.stageNodeListOperationtData) {
      if (item.id === id) {
        nodeList = item.data;
        break;
      }
    }
    for (const item of nodeList) {
      if (item.selectedConstructDays) {
        item['constructDays'] = item.selectedConstructDays.value;
      }
      if (!item.daysOfStart || !item.constructDays || item.daysOfStart > constructDays) {
        return;
      }
    }

    if (nodeList.length === 0) {
      this.selectNodesError = '请选择节点';
      return;
    }
    this.storage.loading();
    this.templateService.saveStageNode({
      delData: this.deletestageNodeListId, list: nodeList
      , detailStageId: stageId
    }).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          let newData = data.data;
          // 当数据保存成功时  将操作数据保存成原始数据
          for (const item of this.stageNodeListData) {
            if (item.id === id) {
              let temItmeIndex = 0;
              for (const temItme of newData) {
                temItmeIndex++;
                if (temItme.constructDays && temItme.constructDays >= 0) {
                  temItme['selectedConstructDays'] = { code: temItmeIndex, value: temItme.constructDays };
                } else {
                  temItme['selectedConstructDays'] = {};
                }
                let constructDaysOptions = [];
                if (temItme.daysOfStart && temItme.daysOfStart >= 0) {
                  for (let i = 0; i <= constructDays - temItme.daysOfStart; i++) {
                    constructDaysOptions = [...constructDaysOptions, { code: i + 1, value: i + 1 }];
                  }
                }
                temItme['constructDaysOptions'] = JSON.parse(JSON.stringify(constructDaysOptions));
              }
              item.data = JSON.parse(JSON.stringify(newData));
              break;
            }
          }
          this.back('stageList', id);
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
        } else {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: data.msg });
        }
      }
    );
  }

  /**
   * tabview能否进行切换
   */
  onChange(event) {
    if (this.tavNextFlag) {
      this.stageLoadData(event);
      event.open();
    } else {
      this.leaveCheck(event);
    }
  }

  /**
   * 根据tabid 加载数据
   */
  stageLoadData(event) {
    if (event.index === 3) {
      // 数据初始化
      this.stageNodeListData = [];
      this.stageData = [];
      this.loading = true;
      this.templateService.stageAndNodeList(this.baseId).then(
        data => {
          if (data.result) {
            this.loading = false;
            this.temStageData = data.data;
            // 请求施工阶段数据
            for (const item of this.temStageData) {
              let temObj = { ...item };
              temObj['stageEditFlag' + item.id] = false;
              temObj['stageBlocked' + item.id] = false;
              temObj['stageSortNum' + item.id] = item.nodeList.length > 0 ? item.nodeList[item.nodeList.length - 1].sortNum : 0;
              this.stageData = [...this.stageData, temObj];
              let temItmeIndex = 0;
              for (const temItme of item.nodeList) {
                temItmeIndex++;
                if (temItme.constructDays && temItme.constructDays >= 0) {
                  temItme['selectedConstructDays'] = { code: temItmeIndex, value: temItme.constructDays };
                } else {
                  temItme['selectedConstructDays'] = {};
                }

                let constructDaysOptions = [];
                if (temItme.daysOfStart && temItme.daysOfStart >= 0) {
                  for (let i = 0; i <= item.constructDays - temItme.daysOfStart; i++) {
                    constructDaysOptions = [...constructDaysOptions, { code: i + 1, value: i + 1 }];
                  }
                }
                temItme['constructDaysOptions'] = JSON.parse(JSON.stringify(constructDaysOptions));
              }
              this.stageNodeListData = [...this.stageNodeListData, { id: item.id, data: item.nodeList }];
            }
            // 操作的数据集合
            this.stageNodeListOperationtData = JSON.parse(JSON.stringify(this.stageNodeListData));
          } else {
            this.loading = false;
            this.temStageData = [];
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );

    } else if (event.index === 1) {
      // 数据初始化
      this.materialData = [];
      this.loading = true;
      this.templateService.findProductList(this.baseId).then(
        data => {
          if (data.result) {
            this.loading = false;
            this.materialData = data.data;
            // 请求物料批次数据
            for (const item of this.temMaterialData) {
              let temObj = { ...item };
              temObj['materialEditFlag' + item.id] = false;
              temObj['materialeBlocked' + item.id] = false;
              // this.materialData = [...this.materialData, temObj];
            }
            // 操作的数据集合
            this.materialOperationtData = JSON.parse(JSON.stringify(this.materialData));
          } else {
            this.loading = false;
            this.materialData = [];
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );


    } else if (event.index === 2) {
      this.loading = true;
      this.templateService.findScheduleList(this.baseId).then(
        data => {
          if (data.result) {
            this.loading = false;
            this.constructionScheduleData = data.data;
            console.log(this.constructionScheduleData);
            for (let item of this.constructionScheduleData) {
              item['isRequestOption'] = item.isRequestPassItem ? { code: true, name: '是' } : { code: false, name: '否' };
              item['sortNumOfBatchOption'] = item.sortNumOfBatch ? { id: item.sortNumOfBatch, name: item.sortNumOfBatchName } : null;
              item['needPayOption'] = item.needPayCode ? { id: item.needPayCode, name: item.needPayName } : null;
              item['triggerPayOption'] = item.triggerPayCode ? { id: item.triggerPayCode, name: item.triggerPayName } : null;
            }
            // 操作数据 同步原始数据
            this.constructionScheduleOperationtData = JSON.parse(JSON.stringify(this.constructionScheduleData));
          } else {
            this.loading = false;
            this.constructionScheduleData = [];
            this.constructionScheduleOperationtData = [];
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );

      // this.sortNumOfBatchOptions = [
      //   { code: '1', id: '1', name: '第1批物料' },
      //   { code: '2', id: '2', name: '第2批物料' },
      //   { code: '3', id: '3', name: '第3批物料' }
      // ];
      // 到必场批次下拉框数据初始化 调用接口获取
      this.templateService.selectProductNum(this.baseId).then(
        data => {
          if (data.result) {
            this.sortNumOfBatchOptions = [{ id : 0, code: '', name: '' }, ...data.data];
          } else {
            this.sortNumOfBatchOptions = [];
            this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
          }
        }
      );
      // 交款项下拉框数据初始化 调用接口获取
      this.paymentTemplateOptions = [{ code: 0, name: '', id: 0 }, ...this.payNameArr];
      // 必过下拉框数据初始化
      this.isRequestPassItemOptions = [
        { code: true, name: '是' },
        { code: false, name: '否' }
      ];
    }

  }

  /**
    * 根据阶段id 更改阶段设置中阶段的编辑状态
    */
  stageListFlagById(id) {
    for (let item of this.stageData) {
      if (item.id === id) {
        item['stageEditFlag' + id] = !item['stageEditFlag' + id];
      }
    }
  }

  /**
    * 根据物料id 更改物料设置中物料的编辑状态
    */
  materialListFlagById(id) {
    for (let item of this.materialData) {
      if (item.id === id) {
        item['materialEditFlag' + id] = !item['materialEditFlag' + id];
        break;
      }
    }
  }

  /**
   * tab页离开后的验证
   */
  leaveCheck(event) {
    this.storage.makesureService.emit({
      message: '您存在未保存的数据，是否确定离开？',
      header: '提示',
      rejectVisible: true,
      acceptVisible: true,
      acceptLabel: '直接离开',
      rejectLabel: '先保存',
      reject: () => {
      },
      accept: () => {
        const stageid = this.findStageDataHasBlocked();
        const materialId = this.findMaterialDataHasBlocked();
        if (this.acceptanceItemEditFlag) {
          this.back('check');
        } else if (this.editFlag) {
          this.back('info');
        } else if (this.constructionEditFlag) {
          this.back('stage');
        } else if (stageid) {
          this.back('stageList', stageid);
        } else if (materialId) {
          this.back('materialList', materialId);
        } else if (this.constructionScheduleFlag) {
          this.back('construction', materialId);
        } else {
          return;
        }
        this.stageLoadData(event);
        event.open();
      }
    });
  }

  /**
   * 在所有阶段中是否存在处于编辑状态的阶段
   */
  findStageDataHasBlocked() {
    let flag = '';
    for (let item of this.stageData) {
      if (item['stageEditFlag' + item.id]) {
        flag = item.id;
        break;
      }
    }
    return flag;
  }

  /**
   *  在所有批次中是否存在处于编辑状态的批次
   */
  findMaterialDataHasBlocked() {
    let flag = '';
    for (let item of this.materialData) {
      if (item['materialEditFlag' + item.id]) {
        flag = item.id;
        break;
      }
    }
    return flag;
  }

  /**
   * 删除物料的方法
   * @param data 当前物料数据
   * @param id  批次的id
   */
  removeMaterial(data, id) {
    for (let item of this.materialOperationtData) {
      if (item.id === id) {
        item.productDetailList = item.productDetailList.filter((arr) => {
          if (arr.id === data.id) {
            return false;
          } else {
            return true;
          }
        });
        break;
      }

    }

  }


  /**
   * 打开物料选择的弹框
   */
  selectMateria() {
    // 所有已选的物料数据
    let existenceData = [];
    let ids = new Array();
    for (const item of this.materialOperationtData) {
      existenceData = [...existenceData, ...item.productDetailList];
    }
    // 所有已选的物料数据
    for (let index of existenceData) {
      ids.push(index.id);
    }
    // 调用ajax获取物料数据 并吧数据绑定到this.materialTree上
    // 物料树的数据源
    this.storage.loading();
    this.templateService.getTreeByExcept(ids).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.materialTree = data.data.tree;
          // 物料数据加载完成后展开树
          this.expandAll();
          this.MaterialDialog = true;
        } else {
          this.storage.loadout();
          this.materialTree = [];
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }

  /**
   * 错误提示
   * @param msg
   */
  error(msg) {
    this.storage.messageService.emit({ severity: 'error', detail: msg });
  }

  /**
   * 选中的物料数据
   */
  saveSelectedMaterial(id) {
    this.selectedMaterialTree = this.selectedMaterialTree.filter((item) => {
      return !item.children || item.children.length <= 0;
    });
    let materials = [];
    for (let item of this.selectedMaterialTree) {
      let tem = { 'id': item.id, 'name': item.name };
      materials = [...materials, tem];
    }
    for (let item of this.materialOperationtData) {
      if (item.id === id) {
        item.productDetailList = JSON.parse(JSON.stringify([...item.productDetailList, ...materials]));
        break;
      }
    }
    if (materials.length > 0) {
      this.materialListError = '';
    }
    this.selectedMaterialTree = [];
    this.MaterialDialog = false;
  }

  /**
   * 保存批次信息
   * @param id 批次id
   */
  saveMaterial(id) {
    let materialData; // 修改的批次数据
    for (let item of this.materialOperationtData) {
      if (item.id === id) {
        if (this.selectedIsAutoReport) {
          item['isAutoReport'] = this.selectedIsAutoReport.code;
        } else {
          delete item['isAutoReport'];
        }
        materialData = JSON.parse(JSON.stringify(item));
        break;
      }
    }
    if (!this.checkSaveCheckData(materialData)) {
      return;
    }
    // 保存数据ajax
    this.storage.loading();
    this.templateService.updateProductList({ data: materialData }).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          for (let index in this.materialData) {
            if (this.materialData[index].id === id) {
              this.materialData[index] = JSON.parse(JSON.stringify(data.data[0]));
              this.materialData[index]['materialEditFlag' + id] = true;
              break;
            }
          }
          this.back('materialList', id); // 保存成功以后记得调用
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
        } else {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: data.msg });
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }
  /**
   * 是否人工提报验证
   */
  isAutoReportCh(earlyStartDays, daysOfArrive, autoReportDays, maxSupplyCycle) {
    let flag = true;
    let autoReportDay: number = 0;
    if (this.selectedIsAutoReport.code) {
      autoReportDay = Number.parseInt(autoReportDays)
      if (autoReportDays == null) {
        this.autoReportDaysError = '请输入自动提报天数';
        flag = false;
      } else {
        if (Number.parseInt(earlyStartDays) >= (Number.parseInt(autoReportDays) + Number.parseInt(maxSupplyCycle))) {
          this.autoReportDaysError = '';
        } else {
          this.autoReportDaysError = '自动提报天数<=提前启动天数-最大供货周期';
          flag = false;
        }
      }
    } else {
      this.autoReportDaysError = '';
    }
    if (maxSupplyCycle == null) {
      this.maxSupplyCycleError = '请输入最大供货周期';
      flag = false;
    } else {
      if (Number.parseInt(earlyStartDays) >= (autoReportDay + Number.parseInt(maxSupplyCycle))) {
        this.maxSupplyCycleError = '';
      } else {
        this.maxSupplyCycleError = '最大供货周期<=提前启动天数-自动提报天数';
        flag = false;
      }
    }
    if (earlyStartDays == null) {
      this.earlyStartDaysError = '请输入提前启动天数';
      flag = false;
    } else {
      if (earlyStartDays <= daysOfArrive && earlyStartDays >= (autoReportDay + maxSupplyCycle)) {
        this.earlyStartDaysError = '';
      } else {
        this.earlyStartDaysError = '提前启动天数<=第几天到场，且提前启动天数>=自动提报天数+最大供货周期';
        flag = false;
      }
      if (!flag) {
        return;
      }
    }

  }
  /**
   * 保存施工排期
   * @param id 批次id
   */
  scheduleSave() {
    let countDays: number = 0;
    for (let item of this.constructionScheduleOperationtData) {
      if (!item['constructDays']) {
        this.constructDaysError = '请输入施工时长';
        return;
      }
      countDays += Number.parseInt(item['constructDays']);
      item['isRequestPassItem'] = item['isRequestOption'] ? item['isRequestOption']['code'] : false;
      item['sortNumOfBatch'] = item['sortNumOfBatchOption'] ? item['sortNumOfBatchOption']['id'] : null;
      item['sortNumOfBatchName'] = item['sortNumOfBatchOption'] ? item['sortNumOfBatchOption']['name'] : null;
      item['needPayCode'] = item['needPayOption'] ? item['needPayOption']['id'] : null;
      item['needPayName'] = item['needPayOption'] ? item['needPayOption']['name'] : null;
      item['triggerPayCode'] = item['triggerPayOption'] ? item['triggerPayOption']['id'] : null;
      item['triggerPayName'] = item['triggerPayOption'] ? item['triggerPayOption']['name'] : null;
    }
    if (countDays !== this.templateData.constructionLimitDays) {
      this.storage.makesureService.emit({
        message: '标准施工周期不等于施工排期时长总和，请重新修改施工排期！',
        header: '提示',
        rejectVisible: false,
        acceptVisible: false,
        accept: () => {
        }
      });
      return;
    }
    if (this.constructionScheduleOperationtData[this.constructionScheduleOperationtData.length - 1].referenceType !== 1) {
      this.storage.makesureService.emit({
        message: '最后一项应为竣工验收，请修改正确！',
        header: '提示',
        rejectVisible: false,
        acceptVisible: false,
        accept: () => {
        }
      });
      return;
    }

    this.storage.loading();
    this.templateService.saveSchedule({ listData: this.constructionScheduleOperationtData, baseId: this.baseId }).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.constructionScheduleData = JSON.parse(JSON.stringify(data.data));
          for (let item of this.constructionScheduleData) {
            item['isRequestOption'] = item.isRequestPassItem ? { code: true, name: '是' } : { code: false, name: '否' };
            item['sortNumOfBatchOption'] = item.sortNumOfBatch ? { id: item.sortNumOfBatch, name: item.sortNumOfBatchName } : null;
            item['needPayOption'] = item.needPayCode ? { id: item.needPayCode, name: item.needPayName } : null;
            item['triggerPayOption'] = item.triggerPayCode ? { id: item.triggerPayCode, name: item.triggerPayName } : null;
          }
          this.back('construction'); // 保存成功以后记得调用
          this.storage.messageService.emit({ severity: 'success', detail: data.msg });
        } else {
          this.storage.loadout();
          this.storage.messageService.emit({ severity: 'error', detail: data.msg });
        }
      }
    );
    // 保存数据的ajax 新数据要保存到  this.constructionScheduleData
    // this.back('construction'); // 保存成功以后记得调用
  }


  /**
   * 物料树全部展开
   * @param node
   * @param isExpand
   */
  private expandRecursive(node, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.children) {
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }
  // 删除施工阶段提示
  deldata() {

  }
  expandAll() {
    this.materialTree.forEach(node => {
      this.expandRecursive(node, true);
    });
  }

  info(data) {

  }

  confirm() {
  }
  checkAbleAreaTo(param) {
    if (!param) {
      this.useAbleAreaError = '请输入适用面积';
      return;
    } else {
      if (this.templateDataBack['useAbleAreaFrom'] > this.templateDataBack['useAbleAreaTo']) {
        this.useAbleAreaError = '适用面积最大值>=适用面积最小值';
        return;
      } else {
        this.useAbleAreaError = '';
      }
    }
  }
  // 数据校验
  checkSaveData(): boolean {
    let flag = true;
    if (!this.templateDataBack['name']) {
      flag = false;
      this.nameError = '请输入名称';
    } else {
      this.nameError = '';
    }
    if (!this.templateDataBack['constructionLimitDays']) {
      flag = false;
      this.constructionLimitDaysError = '请输入标准施工周期';
    } else {
      this.constructionLimitDaysError = '';
    }
    if (!this.templateDataBack['constructionLimitDaysFrom'] && !this.templateDataBack['constructionLimitDaysTo']) {
      flag = false;
      this.constructionLimitError = '请输入施工周期范围';
    } else {
      if (this.templateDataBack['constructionLimitDaysTo'] < this.templateDataBack['constructionLimitDays'] ||
        this.templateDataBack['constructionLimitDaysFrom'] > this.templateDataBack['constructionLimitDays']) {
        flag = false;
        this.constructionLimitError = '施工范围最小值<=标准周期，施工范围最大值>=标准周期';
      } else {
        this.constructionLimitError = '';
      }
    }
    if (!this.templateDataBack['useAbleAreaFrom']) {
      flag = false;
      this.useAbleAreaError = '请输入适用面积！';
    } else {
      this.useAbleAreaError = '';
    }
    if (!this.templateDataBack['useAbleAreaTo']) {
      flag = false;
      this.useAbleAreaError = '请输入适用面积';
    } else {
      if (this.templateDataBack['useAbleAreaFrom'] > this.templateDataBack['useAbleAreaTo']) {
        flag = false;
        this.useAbleAreaError = '适用面积最大值>=适用面积最小值';
      } else {
        this.useAbleAreaError = '';
      }
    }
    if (this.templateDataBack['priceTemplateId'].length === 0) {
      flag = false;
      this.priceTemplateError = '请选择报价模板！';
    } else {
      this.priceTemplateError = '';
    }
    if (this.templateDataBack['organizationCode'].length === 0) {
      flag = false;
      this.organizationError = '请选择适用组织';
    } else {
      this.organizationError = '';
    }
    if (!(this.selectedPayTemplateName && this.selectedPayTemplateName['code'])) {
      flag = false;
      this.payTemplateError = '请选择交款模板';
    } else {
      this.payTemplateError = '';
    }
    if (!this.templateDataBack['deliveryBatchNo']) {
      flag = false;
      this.deliveryBatchNoError = '请输入送货批次';
    } else {
      this.deliveryBatchNoError = '';
    }
    return flag;
  }
  // 校验物料配送
  checkSaveCheckData(data): boolean {
    let flag = true;
    if (!data['daysOfArrive']) {
      flag = false;
      this.daysOfArriveError = '请输入第几天到场';
    } else {
      this.daysOfArriveError = '';
    }
    let autoReportDay: number = 0;
    if (this.selectedIsAutoReport.code === true) {
      autoReportDay = Number.parseInt(data['autoReportDays'])
    }
    if (!data['earlyStartDays']) {
      flag = false;
      this.earlyStartDaysError = '请输入提前启动天数';
    } else {
      if (Number.parseInt(data['earlyStartDays']) < Number.parseInt(data['daysOfArrive']) &&
        Number.parseInt(data['earlyStartDays']) >= (autoReportDay + Number.parseInt(data['maxSupplyCycle']))) {
        this.earlyStartDaysError = '';
      } else {
        flag = false;
        this.earlyStartDaysError = '提前启动天数<第几天到场，且提前启动天数>=自动提报天数+最大供货周期';
      }
    }
    if (this.selectedIsAutoReport.code) {
      if (!data['autoReportDays']) {
        flag = false;
        this.autoReportDaysError = '请输入自动提报天数';
      } else {
        if (Number.parseInt(data['earlyStartDays']) >= (autoReportDay + Number.parseInt(data['maxSupplyCycle']))) {
          this.autoReportDaysError = '';
        } else {
          flag = false;
          this.autoReportDaysError = '自动提报天数<=提前启动天数-最大供货周期';
        }
      }
    }
    if (!data['maxSupplyCycle']) {
      flag = false;
      this.maxSupplyCycleError = '请输入最大供货周期';
    } else {
      if (Number.parseInt(data['earlyStartDays']) >= (autoReportDay + Number.parseInt(data['maxSupplyCycle']))) {
        this.maxSupplyCycleError = '';
      } else {
        flag = false;
        this.maxSupplyCycleError = '最大供货周期<=提前启动天数-自动提报天数';
      }
    }
    if (data['productDetailList'].length === 0) {
      flag = false;
      this.materialListError = '请选择物料组';
    } else {
      this.materialListError = '';
    }
    return flag;
  }
  // 校验施工排期
  checkScheduleSaveData(data): boolean {
    let flag = true;
    if (!data.constructDays) {
      flag = false;
      this.constructDaysError = '施工时长不能为空！';
    } else {
      this.constructDaysError = '';
    }
    return flag;
  }
  // 把错误提示设置为空
  setErrorNull() {
    this.nameError = '';
    this.constructionLimitDaysError = ''; // 标准施工周期错误提示
    this.constructionLimitError = ''; // 施工周期范围错误提示
    this.useAbleAreaError = ''; // 适用面积错误提示
    this.priceTemplateError = ''; // 报价模板错误提示
    this.payTemplateError = ''; // 交款模板错误提示
    this.deliveryBatchNoError = ''; // 送货批次错误提示
    this.daysOfArriveError = '';
    this.earlyStartDaysError = '';
    this.autoReportDaysError = '';
    this.materialListError = '';
    this.maxSupplyCycleError = '';
  }
  // 施工阶段提示
  checkIsNull(name) {
    if (!name) {
      return '请输入名称';
    } else {
      if (name.length > 4) {
        return '名称不超过4个字';
      }
    }

  }
  // 施工阶段红框显示
  checkName(name) {
    if (!name) {
      return true;
    } else {
      if (name.length > 4) {
        return true;
      }
    }
    return false;
  }
  // 施工排期提示
  checkDaysIsNull(days) {
    if (!days) {
      return '请输入施工时长/天';
    } else {
      if (days.length > 5) {
        return '最大长度5';
      } else {
        if (isNaN(days)) {
          return '请输入正确的施工时长/天';
        }
      }
    }

  }
  // 施工排期红框显示
  checkDays(days) {
    if (!days) {
      return true;
    } else {
      if (days.length > 5) {
        return true;
      } else {
        if (isNaN(days)) {
          return true;
        }
      }
    }
    return false;
  }

  // 施工阶段提示
  checkConstructDaysIsNull(days) {
    if (!days) {
      return '请输入施工时长/天';
    } else {
      if (days.length > 5) {
        return '最大长度5';
      } else {
        if (isNaN(days)) {
          return '请输入正确的施工时长/天';
        }
      }
    }

  }
  // 施工阶段红框显示
  checkConstructDays(days) {
    if (!days) {
      return true;
    } else {
      if (days.length > 5) {
        return true;
      } else {
        if (isNaN(days)) {
          return true;
        }
      }
    }
    return false;
  }
  // 施工阶段提示
  checkDaysOfStartIsNull(days, constructDays) {
    if (!days) {
      return '请输入第几天开始';
    } else {
      if (days > constructDays) {
        return '不得大于该阶段的施工时长';
      } else {
        for (let i = 0; i <= constructDays - days; i++) {
        }
        this.daysOfStartOptions = [];
      }
    }

  }
  // 施工阶段红框显示
  checkDaysOfStart(days, constructDays) {
    if (!days) {
      return true;
    } else {
      if (days.length > 5) {
        return true;
      } else {
        if (isNaN(days)) {
          return true;
        }
      }
      if (days > constructDays) {
        return true;
      }
    }
    return false;
  }
  // 名称唯一性校验
  checkNameUnique(param) {
    if (!param) {
      this.nameError = '请输入名称';
      return;
    }
    this.templateDataBack['id'] = this.baseId;
    this.templateService.checkNameUniqueForUpdata({ data: this.templateDataBack }).then(
      result => {
        if (result.result) {
          this.nameError = '';
        } else {
          this.nameError = result.msg;
        }
      }
    );
  }
  // 校验标准施工周期
  checkLimitDays(param) {
    if (!param) {
      this.constructionLimitDaysError = '请输入标准施工周期';
      return;
    } else {
      if (this.templateData.sumConstructDays !== this.templateDataBack.constructionLimitDays) {
        this.constructionLimitDaysError = '标准施工周期不等于施工排期时长总和，模板禁用，请重新修改施工排期！';
      } else {
        this.constructionLimitDaysError = '';
      }
    }
  }
  // 校施工周期最小值
  checkDaysFrom(param) {
    if (!param) {
      this.constructionLimitError = '请输入施工周期范围';
      return;
    } else {
      if (param > this.templateDataBack['constructionLimitDays']) {
        this.constructionLimitError = '施工范围最小值<=标准周期，施工范围最大值>=标准周期';
        return;
      } else {
        this.constructionLimitError = '';
      }
      if (param > this.templateDataBack['constructionLimitDays']) {
        this.constructionLimitError = '施工范围最小值<=标准周期，施工范围最大值>=标准周期';
        return;
      } else {
        this.constructionLimitError = '';
      }
    }
  }
  // 校施工周期最大值
  checkDaysTo(param) {
    if (!param) {
      this.constructionLimitError = '请输入施工周期范围';
      return;
    } else {
      if (this.templateDataBack['constructionLimitDaysFrom'] > param) {
        this.constructionLimitError = '施工范围最大值>=施工范围最小值';
        return;
      } else {
        this.constructionLimitError = '';
      }
      if (this.templateDataBack['constructionLimitDays'] > param) {
        this.constructionLimitError = '施工范围最小值<=标准周期，施工范围最大值>=标准周期';
        return;
      } else {
        this.constructionLimitError = '';
      }
    }
  }
  // 校验 适用面积
  checkAbleArea(param) {
    if (!param) {
      this.useAbleAreaError = '请输入适用面积';
      return;
    } else {
      if (this.templateDataBack['useAbleAreaFrom'] > this.templateDataBack['useAbleAreaTo']) {
        this.useAbleAreaError = '适用面积最大值>=适用面积最小值';
        return;
      } else {
        this.useAbleAreaError = '';
      }
    }
  }
  // 请输入送货批次
  checkBatchNo(param) {
    if (param == null) {
      this.deliveryBatchNoError = '请输入送货批次';
      return;
    } else {
      this.deliveryBatchNoError = '';
    }
  }
  // 请输入第几天到场
  checkDaysOfArrive(param, earlyStartDays) {
    if (param == null) {
      this.daysOfArriveError = '请输入第几天到场';
      return;
    } else {
      if (earlyStartDays >= param) {
        this.daysOfArriveError = '第几天到场>提前启动天数';
        return;
      } else {
        this.daysOfArriveError = '';
      }
    }
  }
  // 请输入提前启动天数
  checkEarlyStartDays(earlyStartDays, daysOfArrive, autoReportDays, maxSupplyCycle) {
    let autoReportDay: number = 0;
    if (this.selectedIsAutoReport.code === true) {
      autoReportDay = Number.parseInt(autoReportDays)
    }
    if (earlyStartDays == null) {
      this.earlyStartDaysError = '请输入提前启动天数';
      return;
    } else {
      if (earlyStartDays < daysOfArrive && earlyStartDays >= (autoReportDay + maxSupplyCycle)) {
        this.earlyStartDaysError = '';
      } else {
        this.earlyStartDaysError = '提前启动天数<第几天到场，且提前启动天数>=自动提报天数+最大供货周期';
        return;
      }
    }
  }

  // 请输入自动提报天数
  checkAutoReportDays(earlyStartDays, autoReportDays, maxSupplyCycle) {
    if (this.selectedIsAutoReport.code === false) {
      return;
    }
    if (autoReportDays == null) {
      this.autoReportDaysError = '请输入自动提报天数';
      return;
    } else {
      if (Number.parseInt(earlyStartDays) >= (Number.parseInt(autoReportDays) + Number.parseInt(maxSupplyCycle))) {
        this.autoReportDaysError = '';
      } else {
        this.autoReportDaysError = '自动提报天数<=提前启动天数-最大供货周期';
        return;
      }
    }
  }
  // 请输入最大供货周期
  checkMaxSupplyCycle(earlyStartDays, autoReportDays, maxSupplyCycle) {
    let autoReportDay: number = 0;
    if (this.selectedIsAutoReport.code === true) {
      autoReportDay = Number.parseInt(autoReportDays)
    }
    if (maxSupplyCycle == null) {
      this.maxSupplyCycleError = '请输入最大供货周期';
      return;
    } else {
      if (Number.parseInt(earlyStartDays) >= (autoReportDay + Number.parseInt(maxSupplyCycle))) {
        this.maxSupplyCycleError = '';
      } else {
        this.maxSupplyCycleError = '最大供货周期<=提前启动天数-自动提报天数';
        return;
      }
    }
  }
  focuLimitDays() {
    if (this.constructionLimitDaysError !== '标准施工周期不等于施工排期时长总和，模板禁用，请重新修改施工排期！') {
      this.constructionLimitDaysError = '';
    }
  }

  /**
   * 保存修改前的dayOFStart
   */
  saveEditDayOfStart(data) {
    this.editDayOfStart = data;
  }




  /**
 * 打开组织选择的弹框
 */
  selectOrganization() {
    // 所有已选的组织数据
    let codes = new Array();
    // 所有已选的组织数据
    // 所有已选的物料数据
    let existenceData = [];
    existenceData = JSON.parse(JSON.stringify([...this.organizationOperationtData, ...this.organizationOperationtData]));
    for (let index of this.organizationOperationtData) {
      codes.push(index.code);
    }
    // 调用ajax获取组织数据 并吧数据绑定到this.materialTree上
    // 组织树的数据源
    this.storage.loading();
    this.templateService.loadOrganization(codes).then(
      data => {
        if (data.result) {
          this.storage.loadout();
          this.organizationTree = data.data;
          // 组织数据加载完成后展开树
          this.expandOrgAll();
          this.organizationDialog = true;
        } else {
          this.storage.loadout();
          this.organizationTree = [];
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }
  expandOrgAll() {
    this.organizationTree.forEach(node => {
      this.expandOrgRecursive(node, true);
    });
  }

  /**
 * 组织树全部展开
 * @param node
 * @param isExpand
 */
  private expandOrgRecursive(node, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.children) {
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

  /**
 * 选中的组织数据
 */
  saveSelectedOrganization(id) {
    // this.selectedOrganizationTree = this.selectedOrganizationTree.filter((item) => {
    //   return !item.children || item.children.length <= 0;
    // });
    let materials = [];
    for (let item of this.selectedOrganizationTree) {
      let tem = { 'code': item.code, 'name': item.label };
      materials = [...materials, tem];
    }
    this.orgData = this.organizationOperationtData = JSON.parse(JSON.stringify([...this.organizationOperationtData, ...materials]));
    if (this.organizationOperationtData.length > 0) {
      this.organizationError = '';
    }
    this.selectedOrganizationTree = [];
    this.organizationDialog = false;
  }
  /**
 * 删除组织的方法
 * @param data 当前组织数据
 */
  removeOrganization(data) {
    this.orgData = this.organizationOperationtData = this.organizationOperationtData.filter((arr) => {
      if (arr.code === data.code) {
        return false;
      } else {
        return true;
      }
    });
  }
}
